package com.manning.s2ip.servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext;

import com.manning.s2ip.beans.SqlCode;

public class SeedDatabaseListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent sce) {
		// do nothing
	}

	public void contextInitialized(ServletContextEvent sce) {
		
		WebApplicationContext wac = 
			getWebApplicationContext(sce.getServletContext());
		
		DataSource ds = (DataSource) wac.getBean("dataSource");
		JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
		
		SqlCode sql = (SqlCode) wac.getBean("sqlCode");
		
		jdbcTemplate.execute(sql.getDdl());
		
		for (String insert : sql.getSeed()) {
			jdbcTemplate.update(insert);
		}
	}
}
